/*
 * UpdateFileTask.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.gerengdic.update;


import com.github.droidfu.concurrent.BetterAsyncTask;

import de.studiorutton.access.IProgressListener;
import de.studiorutton.access.Result;
import de.studiorutton.access.Result.ErrorCode;
import android.content.Context;
import android.util.Log;

public class UpdateFileTask extends BetterAsyncTask<Void, Integer, Result>
		implements IProgressListener {
	private final static String TAG = "learningwords";

	private UpdateFile ul;
	private long currentContentLength;
	private long contentLength;
	private IUpdateTaskProgressListener tpl = null;
	private IUpdateTaskEventListener tel = null;
	private boolean checkOnlyForNewer, isNewer;

	public UpdateFileTask(Context context, UpdateFile ul,
			boolean checkOnlyForNewer) {
		super(context);
		this.ul = ul;
		this.checkOnlyForNewer = checkOnlyForNewer;
	}

	@Override
	protected Result doCheckedInBackground(Context context, Void... v)
			throws Exception {
		// Log.d( TAG, "UpdateFileTask: running." );
		Result r = ul.updateFile(checkOnlyForNewer, this);
		// Log.d(TAG, "Status: " + r.status + " Message:" + r.msg );
		return r;
	}

	public void notifyProgresss(int calculateProgress,
			long currentContentLength, long contentLength) {
		publishProgress(calculateProgress / 10);
		this.currentContentLength = currentContentLength;
		this.contentLength = contentLength;
	}

	@Override
	public void onProgressUpdate(Integer... progress) {
//		Log.d(TAG, "UpdateFileTask:onProgressUpdate: progress = " + progress[0]);
		if (tpl != null)
			tpl.notifyProgress(progress[0], currentContentLength, contentLength);
	}

	public void setCallbacks(IUpdateTaskProgressListener tpl,
			IUpdateTaskEventListener tel) {
		this.tpl = tpl;
		this.tel = tel;
	}

	@Override
	protected void after(Context ctx, Result res) {

		if (!res.isError() && !checkOnlyForNewer) {
			if (tpl != null)
				tpl.notifyProgress(10000, contentLength, contentLength);
		}
		if (checkOnlyForNewer) {
			if ( tel != null )
				tel.notifyNewer(res);
			return;
		}

		if (tel != null) {
			tel.notifyTaskEnded(res);
		}
	}

	@Override
	public void onCancelled() {
		// Log.d( TAG, "UpdateFileTask:onCancelled" );
		ul.cancelUpdateFile();
		if (tel != null) {
			Result res = new Result(Result.STATUS_CANCELLED,
					ErrorCode.STATUS_DOWNLOAD_WAS_CANCELLED);
			// Log.d( TAG,
			// "UpdateFileTask:onCancelled tel.notifyTaskEnded res = " +
			// res.status );
			tel.notifyTaskEnded(res);
		}
	}

	@Override
	protected void handleError(Context arg0, Exception arg1) {
		if (tel != null) {
			Result res = new Result(Result.ERROR_LOCAL_ERROR,
					ErrorCode.ERROR_DURING_DOWNLOAD, arg1.getMessage());
			tel.notifyTaskEnded(res);
		}
	}

}
